package com.snail.learn.roketmq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MessageSelector;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

public class ConsumerDemo {

    public static void main(String[] args) {
//        try {
//            startConsumer();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        try {
            startSeqConsumer();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void startConsumer() throws Exception {
//        1.创建消费者Consumer，指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("snailConsumerTestGroup");
//        2.指定Nameserver地址
        consumer.setNamesrvAddr("localhost:9876");
//        3.订阅主题和Tag
        consumer.subscribe("demoTopic", "seqTag");
        consumer.setMessageModel(MessageModel.CLUSTERING); // 负载均衡模式（默认）
//        consumer.setMessageModel(MessageModel.BROADCASTING);  // 广播模式
//        4.设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgList, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt msg : msgList) {
                    System.out.println(new String(msg.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
//        5.启动消费者Consumer
        consumer.start();
    }


    public static void startSeqConsumer() throws Exception {
//        1.创建消费者Consumer，指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("snailConsumerTestGroup");
//        2.指定Nameserver地址
        consumer.setNamesrvAddr("localhost:9876");
//        3.订阅主题和Tag
//        consumer.subscribe("demoTopic", "seqTag");
        consumer.subscribe("demoTopic", MessageSelector.bySql("i>5"));
//        4.设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
                for (MessageExt msg : list) {
                    System.out.println(consumeOrderlyContext.getMessageQueue().getQueueId() +
                            "," + Thread.currentThread().getName() +
                            ":" + new String(msg.getBody()));
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
//        5.启动消费者Consumer
        consumer.start();
    }

}
